﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace Apps.Yunwei.Views
{
    public partial class ImageSelector : ChildWindow
    {
        public string Source
        {
            get { return (string)GetValue(SourceProperty); }
            set { SetValue(SourceProperty, value); }
        }

        public static readonly DependencyProperty SourceProperty =
            DependencyProperty.Register("Source", typeof(string), typeof(ImageSelector), null);

        const string BASE_DIR = "clientbin";
        string icon1;
        public ImageSelector()
        {
            InitializeComponent();

            Loaded += new RoutedEventHandler(ImageSelector_Loaded);
        }
        void ImageSelector_Loaded(object sender, RoutedEventArgs e)
        {
            text.SetBinding(TextBox.TextProperty, new Binding(Source) { Mode = BindingMode.TwoWay });
            icon1 = text.Text;
            RequestDirs();
        }
        // 请求图片目录清单
        private void RequestDirs()
        {
            busyIndicator.IsBusy = true;
            Q.ConfigManager.RequestCatalogDirs((s, ea) =>
            {
                busyIndicator.IsBusy = false;
                cmb.ItemsSource = ea;
            });
        }
        // 请求图片清单
        private void RequestImages(string path)
        {
            busyIndicator.IsBusy = true;
            Q.ConfigManager.RequestCatalogImages(path, (s, ea) =>
            {
                busyIndicator.IsBusy = false;
                list.ItemsSource = ea;
            });
        }
        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string path = cmb.SelectedValue.ToString();
            RequestImages(path);
        }

        private void list_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (list.SelectedItem == null) return;

            string selectedtext = list.SelectedItem.ToString();
            int index = selectedtext.ToLower().IndexOf(BASE_DIR);
            if (index == -1) return;
            text.Text = selectedtext.Substring(index + BASE_DIR.Length);
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            text.Text = icon1;
            this.DialogResult = false;
        }
        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = true;
        }
    }
}